import { msgError, msgInfo } from '@/utils/msg';
import { isNumeric } from '@/utils/pub';
import { Badge } from 'antd';
import {
  Button,
  LoadPanel,
  NumberBox,
  RadioGroup,
  ScrollView,
  SelectBox,
  TextBox,
  Toolbar,
} from 'devextreme-react';
import { Item } from 'devextreme-react/toolbar';
import { ClickEvent } from 'devextreme/ui/button';
import { CSSProperties, forwardRef, useContext, useEffect, useRef, useState } from 'react';
import { CpasIcon } from '~/public/cpas-ui';
import { consts } from '../../consts';
import {
  LayerExtractType,
  NonStatSampleParameter,
  OverallMode,
  ProjectOverallProps,
  SampleMethod,
  SampleParmeterProps,
  SampleSizeAndAmount,
  SampleSizeMethod,
  SampleStepInfo,
  SystemExtractType,
  WhereSqlParams,
} from '../../typing';
import '../index.less';
import {
  getSampleOverallWhereSQL,
  iniFormQueryAndAdvParams,
} from '../samplingProjectOverallService';
import { SampleStepInfoContext } from '../samplingRecordPopup';
import { textBoxSelectAll } from '../service';
import { GuaranteeCoefficientPopup } from './Coefficient/GuaranteeCoefficientPopup';
import { getGuaranteeCoefficient } from './Coefficient/GuaranteeCoefficientService';
import {
  calcSpecialSampleInfo,
  clearPropsSampleParameterValues,
  getAmountMarjorWhereSql,
  getDefaultLayerRanges,
  getDefaultSampleSortFields,
  getIniSampledResult,
  getIniSampleSizeAndAmount,
  getNeedCalcLayerSampleSize,
  getNonStatSampleMethodList,
  getRedStarHtml,
  getSampledResultTable1,
  getSampleListByWhereSql,
  getSampleSizeAndAmount,
  getToBeTestWhereSql,
  getTrySampleResult,
  getUnimportantWhereSql,
  getValueTextTop500,
  getWhereSqlBySampleList,
} from './NonStatSampleService';
import { LayerSample } from './SampleMethod/LayerSample';
import { ManualSample } from './SampleMethod/ManualSample';
import { RandomSample } from './SampleMethod/RandomSample';
import { SystemSample } from './SampleMethod/SystemSample';
import { getSystemSampleNos } from './SampleMethod/SystemSampleService';
import { ViewSampleListPopup } from './ViewSampleListPopup';

/**
 * 非统计抽样
 */
export const NotStatSample = forwardRef((props: SampleParmeterProps, ref: any) => {
  const guaranteeCoefficientPopupRef = useRef<any>();
  const [isNeedGuaranteeCoefficientPopup, setIsNeedGuaranteeCoefficientPopup] =
    useState<boolean>(false);
  const propsSampleParameterValues = props.sampleStepInfoOfParams?.sampleParameterValues; //编辑传入的
  const viewSampleListPopupRef = useRef<any>();
  //分层抽样
  const layerSampleRef = useRef<any>();
  //用来模拟点击,执行计算
  const btnStatCalcRef = useRef<any>();
  //可容忍错报
  const tolerableMissRef = useRef<any>();
  //任意选样
  const manualSampleRef = useRef<any>();
  const [isNeedViewSampleListPopup, setIsNeedViewSampleListPopup] = useState<boolean>(false);
  //上级传入的抽样参数(注:此组件中sampleStepInfo.sampleParameterValues值不可用,下一步才可用)
  const sampleStepInfo: SampleStepInfo = useContext(SampleStepInfoContext);

  const [loading, setLoading] = useState<boolean>(false);
  //非统计抽样参数
  const [nonStatSampleParameter, setNonStatSampleParameter] = useState<NonStatSampleParameter>(
    () => {
      let nonStatSampleParameter2: NonStatSampleParameter = {
        tolerableMiss: 0,
        amountMajorMin: 0,
        unimportantMax: 0,
        majorMisstatementRisk: '',
        otherSubstantiveRisk: '',
        measurementSampleSize: 0, //sampleStepInfo.projectOverallProps?.curSampleTableTotalCount || 0,
        sampleMethod: SampleMethod.random,

        specialAmountSum: 0, //特殊样本 金额合计
        specialSampleSize: 0, //特殊样本 个数
        specialSampledNumFields: {}, //特殊样本 已抽样字段统计值

        amountMajorAmountSum: 0, //金额重大样本 金额合计
        amountMajorSampleSize: 0, //金额重大样本  个数
        amountMajorSampledNumFields: {}, //金额重大样本 已抽样字段统计值

        unimportantAmountSum: 0, //极不重要样本 金额合计
        unimportantSampleSize: 0, //极不重要样本  个数

        toBeTestAmountSum: 0, //待测试的金额合计
        toBeTestSampleSize: 0, //待测试的个数

        guaranteeCoefficient: 0, //    保证系数

        randomSampleParams: {
          extractNumber: 0,
          useReproducible: true,
          seed: Math.floor(Math.random() * consts.randomSeed), //一万以内的随机数
        }, //随机
        systemSampleParams: {
          //系统
          sampleSortFields: getDefaultSampleSortFields(sampleStepInfo.projectOverallProps),
          extractType: SystemExtractType.asc,
          interval: 0,
          extractNumber: 0,
        },
        //分层抽样
        layerSampleParams: {
          extractType: LayerExtractType.amountBigToSmall,
          layerRanges: getDefaultLayerRanges(sampleStepInfo, 0, 0, 0), //toBeTestSampleSize
          // isManualEdit: false,
        },
        //任意抽样
        manualSampleParams: {
          sampledAmountSum: 0,
          sampledSize: 0,
          sampledList: [],
          manualWhereSql: '',
          sampleTextFieldValues: [],
        },
        //样本列表手工追加的样本 参数
        manualAddParams: {
          sampledAmountSum: 0,
          sampledSize: 0,
          sampledList: [],
          manualWhereSql: '',
          sampleTextFieldValues: [],
        },
        sampledResult: getIniSampledResult(), //抽样结果,不包含 重大项目和特殊项目
        sampleSizeMethod:
          window.main.mainObject?.getUserConfig()?.auditSample?.sampleSizeMethod ||
          SampleSizeMethod.systemOut, //样本量计算方式
      };
      //window.main.mainObject?.getUserConfig()?.auditSample?.sampleSizeMethod
      //如果有传入参数,要合并
      if (props.sampleStepInfoOfParams?.sampleParameterValues) {
        nonStatSampleParameter2 = {
          ...nonStatSampleParameter2,
          ...props.sampleStepInfoOfParams.sampleParameterValues,
        };
      }

      calcAmountSampleSize(nonStatSampleParameter2);

      return nonStatSampleParameter2;
    },
  );

  //是否系统外计算样本量
  const isSystemOutCalc = nonStatSampleParameter.sampleSizeMethod == SampleSizeMethod.systemOut;
  const isSystemOutCalcDisplay = isSystemOutCalc ? 'none' : '';
  const systemOutHint =
    window.main.mainObject?.getUserConfig()?.auditSample?.systemOutHint ||
    '请使用带宏的样本计算器计算';

  const sampleMethodOnValueChanged = (e: any) => {
    calcAmountSampleSize();
    //让手工重算吧
    /*   if (e.value == SampleMethod.layer) {
              //如果是层次抽样要重算未抽样数量
              layerSampleRef.current?.reCalcUnSampleSize();
          } */
    setNonStatSampleParameter({ ...nonStatSampleParameter, sampleMethod: e.value });
  };
  /*  function window_message_event(e: any) {
         const params = e.data; //jsonObject
         if (params.msgType == 'layerSampleReCalcUnSampleSize') {
             layerSampleRef.current?.reCalcUnSampleSize();
         }
     }*/
  useEffect(() => {
    if (ref) {
      ref.current = {
        getSampleParameterValues: () => {
          return nonStatSampleParameter;
        },
        setSampleParameterValues: setNonStatSampleParameter,

        calcAmountSampleSizeAndUpdate: async () => {
          //计算重大金额和极不重要金额
          await btnStatCalcRef.current.click(); //第1次,不行
          await btnStatCalcRef.current.click(); //第2次,不行
          await btnStatCalcRef.current.click(); //第3,才行
        },
      };
    }
  }, [nonStatSampleParameter]);

  useEffect(() => {
    const layerRanges = nonStatSampleParameter.layerSampleParams?.layerRanges;
    if (layerRanges?.length == 1 && layerRanges[0].rangeValue == 0) {
      layerRanges[0].unSampleSize =
        sampleStepInfo.projectOverallProps?.curSampleTableTotalCount || 0;
    }

    let nonStatSampleParameter2: NonStatSampleParameter = {
      ...nonStatSampleParameter,
      systemSampleParams: {
        ...nonStatSampleParameter.systemSampleParams,
        sampleSortFields: getDefaultSampleSortFields(sampleStepInfo.projectOverallProps),
      },
      measurementSampleSize: 0,
      layerSampleParams: {
        ...nonStatSampleParameter.layerSampleParams,
        layerRanges: layerRanges,
      },
    };
    //如果有传入参数,要合并
    if (props.sampleStepInfoOfParams?.sampleParameterValues) {
      nonStatSampleParameter2 = {
        ...nonStatSampleParameter2,
        ...props.sampleStepInfoOfParams.sampleParameterValues,
      };
      calcAmountSampleSize(nonStatSampleParameter2);
    }

    //debugger
    //非统计抽样参数
    setNonStatSampleParameter(nonStatSampleParameter2);
  }, [
    sampleStepInfo.projectOverallProps?.curSampleTable,
    sampleStepInfo.projectOverallProps?.curSampleTableTotalCount,
  ]);
  /**
   * 保证系数表
   */
  function openGuaranteeCoefficientPopup() {
    setIsNeedGuaranteeCoefficientPopup(true);
    const interval = setInterval(() => {
      if (guaranteeCoefficientPopupRef.current) {
        clearInterval(interval);
        guaranteeCoefficientPopupRef.current.show({
          setIsNeedGuaranteeCoefficientPopup,
        });
      }
    }, 10);
  }
  // const significantMissValue = nonStatSampleParameter.guaranteeCoefficient?.significantMissValue;
  const sampleMethodStyle = {
    marginTop: 5,
    marginLeft: -0,
    marginRight: 0,
    padding: 0,
    borderRadius: 5,
  };
  /**
   * 查看样本界面
   */
  const viewSampleListByWhereSql = (fieldTitle: string, sampleSize?: number, whereSql?: string) => {
    if (sampleSize == 0) {
      return msgError(fieldTitle + ' 样本为空');
    }
    setIsNeedViewSampleListPopup(true);
    const projectOverallProps: ProjectOverallProps = sampleStepInfo.projectOverallProps
      ? JSON.parse(JSON.stringify(sampleStepInfo.projectOverallProps))
      : {};

    const overallWhereSQL = getSampleOverallWhereSQL(
      projectOverallProps?.curWhereSqlParams as WhereSqlParams,
    );

    projectOverallProps.overallMode = OverallMode.view;
    projectOverallProps.fixedWhereSql = overallWhereSQL + whereSql;
    //初始化界面查询参数和高级查询参数;
    iniFormQueryAndAdvParams(projectOverallProps);
    const interval = setInterval(() => {
      if (viewSampleListPopupRef.current) {
        clearInterval(interval);

        viewSampleListPopupRef.current.show({
          title: fieldTitle,
          sampleProjectOverallProps: projectOverallProps,
          setIsNeedViewSampleListPopup: setIsNeedViewSampleListPopup,
        });
      }
    }, 10);
  };

  //特殊样本
  function selectSpecialSampleListPopup(e: ClickEvent): void {
    setIsNeedViewSampleListPopup(true);
    const projectOverallProps = sampleStepInfo.projectOverallProps
      ? JSON.parse(JSON.stringify(sampleStepInfo.projectOverallProps))
      : {};
      
    const sampleWhereSQL = getSampleOverallWhereSQL(
      projectOverallProps?.curWhereSqlParams as WhereSqlParams,
    );
    projectOverallProps.overallMode = OverallMode.select;
    projectOverallProps.fixedWhereSql = sampleWhereSQL;
    //初始化界面查询参数和高级查询参数;
    iniFormQueryAndAdvParams(projectOverallProps);
    const interval = setInterval(async () => {
      if (viewSampleListPopupRef.current) {
        clearInterval(interval);
        
        const specialSampleList = nonStatSampleParameter.specialWhereSql
          ? await getSampleListByWhereSql(sampleStepInfo, nonStatSampleParameter.specialWhereSql)
          : [];

        viewSampleListPopupRef.current.show({
          title: '选择特定样本',
          sampleProjectOverallProps: projectOverallProps,
          specialSampleList: specialSampleList, //nonStatSampleParameter.specialSampleList || [],
          setIsNeedViewSampleListPopup: setIsNeedViewSampleListPopup,
          okCallback: async (newSpecialSampleList: any[]) => {
            // 计算特殊样本信息
            await calcSpecialSampleInfo(
              sampleStepInfo,
              nonStatSampleParameter,
              newSpecialSampleList,
              true,
              calcAmountSampleSize,
            );

            setNonStatSampleParameter({ ...nonStatSampleParameter });
            setIsNeedViewSampleListPopup(false);
          },
        });
      }
    }, 10);
  }
  const thStyle: CSSProperties = {
    textAlign: 'center',
    fontSize: 16,
    fontWeight: 'bold',
    border: '1px solid #ccc',
    backgroundColor: '#f5f5f5',
  };
  const tableStye: CSSProperties = {
    /*  border: '1px solid #ccc', */ width: '100%',
    borderRadius: 5,
  };
  /**
   * 金额重在大小和金额 if (!inNonStatSampleParameter) inNonStatSampleParameter = nonStatSampleParameter;
   */
  async function getSampleSizeAndAmountOfAmountMajorMin(
    inNonStatSampleParameter?: NonStatSampleParameter,
    notCalcAndSet?: boolean,
  ) {
    if (!inNonStatSampleParameter) inNonStatSampleParameter = nonStatSampleParameter;

    inNonStatSampleParameter.amountMajorWhereSql = '';
    let sampleSizeAndAmount: SampleSizeAndAmount = getIniSampleSizeAndAmount();
    if (inNonStatSampleParameter.amountMajorMin != 0) {
      inNonStatSampleParameter.amountMajorWhereSql = getAmountMarjorWhereSql(
        sampleStepInfo,
        inNonStatSampleParameter,
      );
      sampleSizeAndAmount = await getSampleSizeAndAmount(
        sampleStepInfo,
        inNonStatSampleParameter.amountMajorWhereSql,
      );
      inNonStatSampleParameter.amountMajorSampledNumFields = {
        ...sampleSizeAndAmount.sampledNumFields,
      };
    }
    inNonStatSampleParameter.amountMajorAmountSum = sampleSizeAndAmount.amountSum;
    inNonStatSampleParameter.amountMajorSampleSize = sampleSizeAndAmount.sampleSize;
    //再计算一次 2024-11-11
    const specialSampleList = inNonStatSampleParameter.specialWhereSql
      ? await getSampleListByWhereSql(sampleStepInfo, inNonStatSampleParameter.specialWhereSql)
      : [];

    await calcSpecialSampleInfo(
      sampleStepInfo,
      inNonStatSampleParameter,
      specialSampleList,
      false,
      undefined,
    );

    if (!notCalcAndSet) {
      calcAmountSampleSize(inNonStatSampleParameter);
      setNonStatSampleParameter({ ...inNonStatSampleParameter });
    }
  }
  /**
   * 金额重在大小和金额
   */
  async function getSampleSizeAndAmountOfUnimportantMax(
    inNonStatSampleParameter?: NonStatSampleParameter,
    notCalcAndSet?: boolean,
  ) {
    if (!inNonStatSampleParameter) inNonStatSampleParameter = nonStatSampleParameter;
    inNonStatSampleParameter.unimportantWhereSql = '';
    let sampleSizeAndAmount: SampleSizeAndAmount = getIniSampleSizeAndAmount();
    if (inNonStatSampleParameter.unimportantMax != 0) {
      inNonStatSampleParameter.unimportantWhereSql = getUnimportantWhereSql(
        sampleStepInfo,
        inNonStatSampleParameter,
      );
      sampleSizeAndAmount = await getSampleSizeAndAmount(
        sampleStepInfo,
        inNonStatSampleParameter.unimportantWhereSql,
      );
    }
    inNonStatSampleParameter.unimportantAmountSum = sampleSizeAndAmount.amountSum;
    inNonStatSampleParameter.unimportantSampleSize = sampleSizeAndAmount.sampleSize;

    //再计算一次 2024-11-11
    const specialSampleList = inNonStatSampleParameter.specialWhereSql
      ? await getSampleListByWhereSql(sampleStepInfo, inNonStatSampleParameter.specialWhereSql)
      : [];

    await calcSpecialSampleInfo(
      sampleStepInfo,
      inNonStatSampleParameter,
      specialSampleList,
      false,
      undefined,
    );

    if (!notCalcAndSet) {
      calcAmountSampleSize(inNonStatSampleParameter);
      setNonStatSampleParameter({ ...inNonStatSampleParameter });
    }
  }
  //可容忍错报值改变
  async function tolerableMissValueChange() {
    calcAmountSampleSize();
    setNonStatSampleParameter({ ...nonStatSampleParameter });
  }
  async function measurementSampleSizeValueChange() {
    //清除样本编辑参数,为了 只修改样本规模时,才重新计算
    clearPropsSampleParameterValues(propsSampleParameterValues);
    calcAmountSampleSize();
    setNonStatSampleParameter({ ...nonStatSampleParameter });
  }
  /**
   * 获取待测试的金额
   */
  function calcAmountSampleSize(inNonStatSampleParameter?: NonStatSampleParameter) {
    if (!inNonStatSampleParameter) inNonStatSampleParameter = nonStatSampleParameter;

    const old_toBeTestSampleSize = inNonStatSampleParameter.toBeTestSampleSize || 0;
    const old_toBeTestAmountSum = inNonStatSampleParameter.toBeTestAmountSum || 0;
    const old_measurementSampleSize = inNonStatSampleParameter.measurementSampleSize || 0;

    const curSampleTableAmountSum =
      sampleStepInfo.projectOverallProps?.curSampleTableAmountSum || 0; // 1
    const curSampleTableTotalCount =
      sampleStepInfo.projectOverallProps?.curSampleTableTotalCount || 0; //
    //需要测试总体金额
    const { amountMajorAmountSum, specialAmountSum, unimportantAmountSum } =
      inNonStatSampleParameter; //2/3/4行
    inNonStatSampleParameter.toBeTestAmountSum =
      curSampleTableAmountSum - (amountMajorAmountSum || 0);

    inNonStatSampleParameter.toBeTestAmountSum =
      inNonStatSampleParameter.toBeTestAmountSum < 0
        ? 0
        : inNonStatSampleParameter.toBeTestAmountSum;
    //需要测试总体样本
    const { amountMajorSampleSize, specialSampleSize, unimportantSampleSize } =
      inNonStatSampleParameter;
    inNonStatSampleParameter.toBeTestSampleSize =
      curSampleTableTotalCount - (amountMajorSampleSize || 0);
    //如果选择的特殊项目,属于极不重要上限的,则需要增加
    inNonStatSampleParameter.toBeTestSampleSize +=
      inNonStatSampleParameter.lessThanUnimportantMaxSampleSize || 0;
    inNonStatSampleParameter.toBeTestAmountSum +=
      inNonStatSampleParameter.lessThanUnimportantMaxSampleSum || 0;
    //如果选择的特殊项目,属于金额重大的,则需要增加
    inNonStatSampleParameter.toBeTestSampleSize +=
      inNonStatSampleParameter.greaterThanAmountMajorMinSampleSize || 0;
    inNonStatSampleParameter.toBeTestAmountSum +=
      inNonStatSampleParameter.greaterThanAmountMajorMinSampleSum || 0;

    inNonStatSampleParameter.toBeTestSampleSize =
      inNonStatSampleParameter.toBeTestSampleSize -
      (unimportantSampleSize || 0) -
      (specialSampleSize || 0);
    //如果选择的特殊项目,属于金额重大的,则需要增加

    inNonStatSampleParameter.toBeTestAmountSum =
      inNonStatSampleParameter.toBeTestAmountSum -
      (specialAmountSum || 0) -
      (unimportantAmountSum || 0);

    inNonStatSampleParameter.toBeTestSampleSize =
      inNonStatSampleParameter.toBeTestSampleSize < 0
        ? 0
        : inNonStatSampleParameter.toBeTestSampleSize;
    inNonStatSampleParameter.toBeTestWhereSql = getToBeTestWhereSql(inNonStatSampleParameter);

    if (!isSystemOutCalc) {
      //如果系统外计算样本规模大小
      //E.样本规模(E=B*D/C)
      inNonStatSampleParameter.measurementSampleSize = 0;

      if (inNonStatSampleParameter.tolerableMiss) {
        inNonStatSampleParameter.measurementSampleSize = Math.ceil(
          (inNonStatSampleParameter.toBeTestAmountSum *
            (inNonStatSampleParameter.guaranteeCoefficient || 0)) /
            inNonStatSampleParameter.tolerableMiss,
        );
        //取最小值
        inNonStatSampleParameter.measurementSampleSize = Math.min(
          inNonStatSampleParameter.measurementSampleSize,
          inNonStatSampleParameter.toBeTestSampleSize,
        );
      }
    }

    //如果数字为0,则设置为待抽取的样本数量
    if (inNonStatSampleParameter.randomSampleParams) {
      inNonStatSampleParameter.randomSampleParams.extractNumber =
        propsSampleParameterValues?.randomSampleParams?.extractNumber ||
        inNonStatSampleParameter.measurementSampleSize;
    }
    //则设置为待抽取的样本数量
    if (
      inNonStatSampleParameter.ppsSampleParams &&
      inNonStatSampleParameter.measurementSampleSize
    ) {
      inNonStatSampleParameter.ppsSampleParams.extractNumber =
        propsSampleParameterValues?.ppsSampleParams?.extractNumber ||
        inNonStatSampleParameter.measurementSampleSize;
    }
    // console.log('inNonStatSampleParameter.measurementSampleSize',inNonStatSampleParameter.measurementSampleSize)
    // F.重大项目数量(减掉重叠的)

    inNonStatSampleParameter.majorProjectSize =
      (inNonStatSampleParameter.amountMajorSampleSize || 0) +
      (inNonStatSampleParameter.specialSampleSize || 0) -
      (inNonStatSampleParameter.greaterThanAmountMajorMinSampleSize || 0);

    //G.需测试的全部数量(G=E+F)  个数
    inNonStatSampleParameter.needTestAllSampleSize = Math.min(
      (inNonStatSampleParameter.measurementSampleSize || 0) +
        (inNonStatSampleParameter.majorProjectSize || 0),
      curSampleTableTotalCount,
    );

    //分层抽样的参数
    // const layerRanges = inNonStatSampleParameter.layerSampleParams?.layerRanges || [];
    //如果新旧不相同的值,就需要重算
    const isNeedCalcLayerSampleSize = getNeedCalcLayerSampleSize(
      inNonStatSampleParameter,
      old_toBeTestSampleSize,
      old_toBeTestAmountSum,
      old_measurementSampleSize,
    );

    //如果是没有设置过的,使用初始化的
    if (inNonStatSampleParameter.layerSampleParams) {
      const propLayerRanges = propsSampleParameterValues?.layerSampleParams?.layerRanges;
      if (propLayerRanges?.length) {
        inNonStatSampleParameter.layerSampleParams.layerRanges = propLayerRanges;
      } else {
        let needSampleSizeLen = inNonStatSampleParameter.layerSampleParams.layerRanges?.filter(
          (item) => !item.needSampleSize,
        ).length;
        if (
          needSampleSizeLen ||
          isNeedCalcLayerSampleSize ||
          !inNonStatSampleParameter.layerSampleParams.layerRanges?.length
        ) {
          inNonStatSampleParameter.layerSampleParams.layerRanges = getDefaultLayerRanges(
            sampleStepInfo,
            inNonStatSampleParameter.toBeTestSampleSize,
            inNonStatSampleParameter.toBeTestAmountSum,
            inNonStatSampleParameter.measurementSampleSize,
          );
        }
      }
    }

    //系统抽样
    if (inNonStatSampleParameter.systemSampleParams) {
      //如果选择了系统抽样,则设置抽取间隔(如果是编辑的,把编辑带入的值设置为默认值)
      if (propsSampleParameterValues?.systemSampleParams?.extractNumber) {
        inNonStatSampleParameter.systemSampleParams =
          propsSampleParameterValues?.systemSampleParams;
      } else {
        let sampleInterval = 0;
        //样本间隔 = B.待抽样的测试总体(扣除特定项目后)	/  E.样本规模
        //编辑时sampleInterval参数为0,则使用重新计算
        if (inNonStatSampleParameter.measurementSampleSize) {
          sampleInterval = Math.floor(
            inNonStatSampleParameter.toBeTestSampleSize /
              inNonStatSampleParameter.measurementSampleSize,
          );
        }
        if (inNonStatSampleParameter.systemSampleParams) {
          inNonStatSampleParameter.systemSampleParams.interval = sampleInterval;
        }

        const sampleNos = getSystemSampleNos(
          inNonStatSampleParameter.toBeTestSampleSize,
          inNonStatSampleParameter.systemSampleParams?.interval || 0,
          inNonStatSampleParameter.systemSampleParams?.extractType == SystemExtractType.asc,
        );

        inNonStatSampleParameter.systemSampleParams.extractNumber = sampleNos.length;
      }
    }
  }

  /**
   * 抽样的参数
   * @returns
   */
  function getSampleParamsTopTable() {
    return (
      <table className="table-with-borders" style={tableStye}>
        <thead>
          <tr>
            <td
              width="3%"
              style={{ ...thStyle, fontSize: 14, minWidth: 35, paddingLeft: 0, paddingRight: 0 }}
            >
              行次
            </td>
            <td width="27%" style={thStyle}>
              项目
            </td>
            <td width="25%" style={thStyle}>
              参数
            </td>
            <td width="20%" style={thStyle}>
              金额或数值
            </td>
            <td width="10%" style={thStyle}>
              项目数量
            </td>
            <td width="15%" style={thStyle}>
              备注
            </td>
          </tr>
        </thead>
        <tr>
          {/* A.总体（扣除特定项目前） */}
          <td className="text-center">1</td>
          <td className="bolb-font">A.总体（扣除特定项目前）</td>
          <td>{consts.NA}</td>
          <td>
            <NumberBox
              rtlEnabled={true}
              value={sampleStepInfo.projectOverallProps?.curSampleTableAmountSum || 0}
              readOnly={true}
              stylingMode="filled"
              format={consts.numberFormat}
              tabIndex={-1}
            />
          </td>
          <td className="text-center ">
            <a
              title="点击查看样本"
              onClick={() => {
                viewSampleListByWhereSql(
                  `总体样本`,
                  sampleStepInfo.projectOverallProps?.curSampleTableTotalCount ||
                    props.sampleStepInfoOfParams?.projectOverallProps?.curSampleTableTotalCount ||
                    0,
                  '',
                );
              }}
            >
              <span style={{ marginRight: 5 }}>
                {sampleStepInfo.projectOverallProps?.curSampleTableTotalCount ||
                  props.sampleStepInfoOfParams?.projectOverallProps?.curSampleTableTotalCount ||
                  0}
              </span>
              <CpasIcon type="icon-shuxing"></CpasIcon>
            </a>

            {/* <NumberBox value={sampleStepInfo.projectOverallProps?.curSampleTableTotalCount}
                    readOnly={true} stylingMode='filled' format={consts.unitGeFormat}
                /> */}
          </td>
          <td className="auto-font-size">
            <TextBox
              stylingMode="filled"
              readOnly={true}
              value="总体的金额、项目数量"
              tabIndex={-1}
            />
          </td>
        </tr>
        <tr>
          {/* 金额重大下限 */}
          <td className="text-center">2</td>
          <td>减：总体中金额重大的项目</td>
          <td className="itemBoxDispalyCenter" style={{ border: 0 }}>
            <div
              style={{ width: '90px', textAlign: 'left' }}
              title={`大于等于${nonStatSampleParameter.amountMajorMin}`}
            >
              金额重大下限
            </div>
            <NumberBox
              value={nonStatSampleParameter.amountMajorMin}
              format={consts.numberFormat}
              width={'calc(98% - 90px)'}
              min={0}
              onFocusIn={textBoxSelectAll}
              onFocusOut={() => getSampleSizeAndAmountOfAmountMajorMin()}
              onValueChanged={async (e: any) => {
                nonStatSampleParameter.amountMajorMin = e.value;
                setNonStatSampleParameter({ ...nonStatSampleParameter });
              }}
              onEnterKey={() => getSampleSizeAndAmountOfAmountMajorMin()}
            />
          </td>
          <td className="text-center">
            <NumberBox
              rtlEnabled={true}
              value={nonStatSampleParameter.amountMajorAmountSum}
              format={consts.numberFormat}
              readOnly={true}
              tabIndex={-1}
            />
          </td>
          {/* 金额重大下限 个数 */}
          <td className="text-center">
            <a
              title="点击查看样本"
              onClick={() => {
                viewSampleListByWhereSql(
                  `【金额重大下限：${nonStatSampleParameter.amountMajorMin}】样本`,
                  nonStatSampleParameter.amountMajorSampleSize,
                  nonStatSampleParameter.amountMajorWhereSql,
                );
              }}
            >
              <span style={{ marginRight: 5 }}>{nonStatSampleParameter.amountMajorSampleSize}</span>
              <CpasIcon type="icon-shuxing"></CpasIcon>
            </a>

            {/* <NumberBox value={nonStatSampleParameter.amountMajorSampleSize}
                    readOnly={true} stylingMode='filled' format={consts.unitGeFormat}
                /> */}
          </td>
          <td></td>
        </tr>
        <tr>
          {/* 总体中性质特殊的重大项目 */}
          <td className="text-center">3</td>
          <td>　　总体中性质特殊的重大项目</td>
          <td className="itemBoxDispalyCenter">
            <div style={{ width: '90px', textAlign: 'left' }}>特殊重大项目</div>
            <Button
              width="calc(98% - 90px)"
              text={`请选择项目`}
              icon="fieldchooser"
              stylingMode="outlined"
              style={{ marginBottom: 4 }}
              onClick={selectSpecialSampleListPopup}
            ></Button>

            <Badge
              showZero={false}
              style={{ marginLeft: 3, cursor: 'default' }}
              count={nonStatSampleParameter.lessThanUnimportantMaxSampleSize}
              title={`有 ${nonStatSampleParameter.lessThanUnimportantMaxSampleSize} 个属于极不重要项目`}
            />
            <Badge
              showZero={false}
              style={{ marginLeft: 3, cursor: 'default' }}
              count={nonStatSampleParameter.greaterThanAmountMajorMinSampleSize}
              title={`有 ${nonStatSampleParameter.greaterThanAmountMajorMinSampleSize} 个属于金额重大项目`}
            />
          </td>
          <td>
            <NumberBox
              rtlEnabled={true}
              value={nonStatSampleParameter.specialAmountSum}
              format={consts.numberFormat}
              readOnly={true}
              tabIndex={-1}
            />
          </td>
          <td className="text-center">
            <a
              title="点击查看样本"
              onClick={() => {
                viewSampleListByWhereSql(
                  `性质特殊的重大项目样本`,
                  nonStatSampleParameter.specialSampleSize,
                  nonStatSampleParameter.specialWhereSql,
                );
              }}
            >
              <span style={{ marginRight: 5 }}>{nonStatSampleParameter.specialSampleSize}</span>
              <CpasIcon type="icon-shuxing"></CpasIcon>
            </a>
          </td>
          <td></td>
        </tr>
        <tr>
          {/* 总体中极不重要项目 */}
          <td className="text-center">4</td>
          <td>　　总体中极不重要项目</td>
          <td className="itemBoxDispalyCenter" style={{ border: 0 }}>
            <div
              style={{ width: '90px', textAlign: 'left' }}
              title={`小于等于${nonStatSampleParameter.unimportantMax}`}
            >
              极不重要上限
            </div>
            <NumberBox
              value={nonStatSampleParameter.unimportantMax}
              onFocusIn={textBoxSelectAll}
              format={consts.numberFormat}
              min={0}
              width={'calc(98% - 90px)'}
              onFocusOut={() => getSampleSizeAndAmountOfUnimportantMax()}
              onValueChanged={async (e: any) => {
                nonStatSampleParameter.unimportantMax = e.value;
                setNonStatSampleParameter({ ...nonStatSampleParameter });
              }}
              onEnterKey={() => getSampleSizeAndAmountOfUnimportantMax()}
            />
          </td>
          <td>
            <NumberBox
              rtlEnabled={true}
              value={nonStatSampleParameter.unimportantAmountSum}
              readOnly={true}
              stylingMode="filled"
              format={consts.numberFormat}
              tabIndex={-1}
            />
          </td>
          {/* 极不重要个数 */}
          <td className="text-center">
            <a
              title="点击查看样本"
              onClick={() => {
                viewSampleListByWhereSql(
                  `【极不重要上限：${nonStatSampleParameter.unimportantMax}】样本`,
                  nonStatSampleParameter.unimportantSampleSize,
                  nonStatSampleParameter.unimportantWhereSql,
                );
              }}
            >
              <span style={{ marginRight: 5 }}>{nonStatSampleParameter.unimportantSampleSize}</span>
              <CpasIcon type="icon-shuxing"></CpasIcon>
            </a>
          </td>
          <td></td>
        </tr>
        <tr>
          {/* B.待抽样的测试总体（扣除特定项目后） */}
          <td className="text-center">5</td>
          <td className="bolb-font">B.待抽样的测试总体(扣除特定项目后)</td>
          <td>5 = 1 - 2 - 3 - 4</td>
          <td>
            <NumberBox
              rtlEnabled={true}
              value={nonStatSampleParameter.toBeTestAmountSum}
              readOnly={true}
              stylingMode="filled"
              format={consts.numberFormat}
              tabIndex={-1}
            />
          </td>
          <td className="text-center">
            <a
              title="点击查看样本"
              onClick={() => {
                viewSampleListByWhereSql(
                  `【待抽样的测试总体(扣除特定项目后)】样本`,
                  nonStatSampleParameter.toBeTestSampleSize,
                  getToBeTestWhereSql(nonStatSampleParameter),
                );
              }}
            >
              <span style={{ marginRight: 5 }}>{nonStatSampleParameter.toBeTestSampleSize}</span>
              <CpasIcon type="icon-shuxing"></CpasIcon>
            </a>
          </td>
          <td></td>
        </tr>

        <tr style={{ display: isSystemOutCalcDisplay }}>
          {/* C.可容忍错报 */}
          <td className="text-center">6</td>
          <td>C.可容忍错报{/* (重要性的30%-70%) */}</td>
          <td style={{ border: 0 }}>
            <div>{getRedStarHtml()}可容忍错报</div>
          </td>
          <td style={{ padding: 5 }}>
            <NumberBox
              ref={tolerableMissRef}
              value={nonStatSampleParameter.tolerableMiss}
              format={consts.numberFormat}
              rtlEnabled={true}
              onFocusIn={textBoxSelectAll}
              onFocusOut={tolerableMissValueChange}
              onValueChanged={async (e: any) => {
                nonStatSampleParameter.tolerableMiss = e.value;
                setNonStatSampleParameter({ ...nonStatSampleParameter });
              }}
              onEnterKey={tolerableMissValueChange}
            />
          </td>
          <td className="text-center">{consts.NA}</td>
          <td></td>
        </tr>
        <tr style={{ display: isSystemOutCalcDisplay }}>
          {/* D.保证系数 */}
          <td className="text-center">7</td>
          <td>D.保证系数</td>
          <td className="">
            <div className="itemBoxDispalyCenter">
              <div style={{ width: '120px', textAlign: 'left', fontSize: 13 }}>
                {getRedStarHtml()}重大错报风险水平
              </div>
              <SelectBox
                width={'calc(98% - 120px)'}
                dataSource={consts.riskLevelArray}
                valueExpr="value"
                displayExpr="text"
                placeholder="选择"
                //style={{ marginRight: 5 }}
                value={nonStatSampleParameter.majorMisstatementRisk}
                onValueChanged={(e: any) => {
                  nonStatSampleParameter.majorMisstatementRisk = e.value;
                  const { majorMisstatementRisk, otherSubstantiveRisk } = nonStatSampleParameter;
                  if (majorMisstatementRisk && otherSubstantiveRisk) {
                    const guaranteeCoefficient = getGuaranteeCoefficient(
                      majorMisstatementRisk,
                      otherSubstantiveRisk,
                    );
                    if (isNumeric(guaranteeCoefficient)) {
                      nonStatSampleParameter.guaranteeCoefficient = Number(guaranteeCoefficient);
                    }
                  }
                  calcAmountSampleSize();
                  setNonStatSampleParameter({ ...nonStatSampleParameter });
                }}
              />
            </div>
            <div className="itemBoxDispalyCenter" style={{ marginTop: 2 }}>
              <div style={{ width: '120px', textAlign: 'left', fontSize: 13 }}>
                {getRedStarHtml()}其他实质性风险
              </div>
              <SelectBox
                width={'calc(98% - 120px)'}
                dataSource={consts.riskLevelArray}
                valueExpr="value"
                displayExpr="text"
                placeholder="选择"
                value={nonStatSampleParameter.otherSubstantiveRisk}
                //style={{ marginRight: 10 }}
                onValueChanged={(e: any) => {
                  nonStatSampleParameter.otherSubstantiveRisk = e.value;
                  const { majorMisstatementRisk, otherSubstantiveRisk } = nonStatSampleParameter;
                  if (majorMisstatementRisk && otherSubstantiveRisk) {
                    nonStatSampleParameter.guaranteeCoefficient = getGuaranteeCoefficient(
                      majorMisstatementRisk,
                      otherSubstantiveRisk,
                    );
                  }
                  calcAmountSampleSize();
                  setNonStatSampleParameter({ ...nonStatSampleParameter });
                }}
              />
            </div>
          </td>
          <td>
            <NumberBox
              rtlEnabled={true}
              value={nonStatSampleParameter.guaranteeCoefficient}
              readOnly={true}
              stylingMode="filled"
              tabIndex={-1}
            />
          </td>
          <td className="text-center">
            <Button
              hint="查看保证系数表"
              text={`保证系数表`}
              /* icon="help" */ stylingMode="outlined"
              style={{ marginTop: 4 }}
              onClick={openGuaranteeCoefficientPopup}
            ></Button>
          </td>
          <td></td>
        </tr>
        <tr>
          {/*  E.样本规模(E=B*D/C) */}
          <td className="text-center">{isSystemOutCalc ? 6 : 8}</td>
          <td className="bolb-font">E.样本规模{/*  E=B*D/C */}</td>
          <td>{isSystemOutCalc ? systemOutHint : '8 = 5 / 6 * 7'}</td>
          <td className="text-right">{systemOutHint ? '请输入样本规模' : consts.NA}</td>
          <td className="text-center">
            {isSystemOutCalc ? (
              <NumberBox
                value={nonStatSampleParameter.measurementSampleSize}
                //format={consts.numberFormat}
                // rtlEnabled={true}
                min={0}
                max={nonStatSampleParameter.toBeTestSampleSize}
                hint={`样本规模最大值 ${nonStatSampleParameter.toBeTestSampleSize}`}
                onFocusIn={textBoxSelectAll}
                //  onFocusOut={measurementSampleSizeValueChange} 手工输入时不要这个事件

                onValueChange={async (e: any) => {
                  nonStatSampleParameter.measurementSampleSize = e;
                  measurementSampleSizeValueChange();
                }}
                onEnterKey={measurementSampleSizeValueChange}
              />
            ) : (
              nonStatSampleParameter.measurementSampleSize
            )}
          </td>
          <td>
            {nonStatSampleParameter.measurementSampleSize >
              (nonStatSampleParameter.toBeTestSampleSize || 0) && (
              <span style={{ color: 'red' }}>样本规模应小于等于待抽样的测试总体</span>
            )}
          </td>
        </tr>
        <tr>
          {/*  F.重大项目数量 */}
          <td className="text-center">{isSystemOutCalc ? 7 : 9}</td>
          <td>F.重大项目数量</td>
          <td>{isSystemOutCalc ? 7 : 9} = 2 + 3</td>
          <td className="text-right">{consts.NA}</td>
          <td className="text-center">{nonStatSampleParameter.majorProjectSize}</td>
          <td></td>
        </tr>
        <tr>
          {/*  F.重大项目数量 */}
          <td className="text-center">{isSystemOutCalc ? 8 : 10}</td>
          <td className="bolb-font">G.需测试的全部数量{/* (G=E+F) */}</td>
          <td>{isSystemOutCalc ? '8 = 6 + 7' : '10 = 8 + 9'}</td>
          <td className="text-right">{consts.NA}</td>
          <td className="text-center">{nonStatSampleParameter.needTestAllSampleSize}</td>
          <td></td>
        </tr>
      </table>
    );
  }
  return (
    <ScrollView
      id="nonStatSampleParameterScrollview"
      height="100%"
      style={
        {
          /*  border: '1px solid red' */
        }
      }
    >
      <div style={{ width: '99%' }}>
        <button
          id="btnNonStatCalc"
          ref={btnStatCalcRef}
          style={{ display: 'none' }}
          onClick={async () => {
            await getSampleSizeAndAmountOfAmountMajorMin(undefined, true);
            await getSampleSizeAndAmountOfUnimportantMax(undefined, false);
            msgInfo('数据加载中...', 500, undefined, '300px'); //这个界面才更新

            //  calcAmountSampleSize();
            // setNonStatSampleParameter({ ...nonStatSampleParameter });
          }}
        >
          计算
        </button>

        {/* 保证系数表 */}
        {isNeedGuaranteeCoefficientPopup && (
          <GuaranteeCoefficientPopup
            nonStatSampleParameter={nonStatSampleParameter}
            setNonStatSampleParameter={setNonStatSampleParameter}
            ref={guaranteeCoefficientPopupRef}
          />
        )}
        {/* 查看样本 */}
        {isNeedViewSampleListPopup && <ViewSampleListPopup ref={viewSampleListPopupRef} />}
        {/*  抽样参数top表 */}
        {getSampleParamsTopTable()}

        <Toolbar style={{ marginTop: 8 }} id="nonStatSample_SampleMethodToolBar">
          <Item location="before">
            <RadioGroup
              layout="horizontal"
              dataSource={getNonStatSampleMethodList()}
              value={nonStatSampleParameter.sampleMethod}
              onValueChanged={sampleMethodOnValueChanged}
            />
          </Item>
          <Item location="before" locateInMenu={'auto'}>
            <div className="itemBoxDispalyLeft">
              <TextBox
                label={`已抽样本，共 ${nonStatSampleParameter.sampledResult?.sampledSize || 0} 个`}
                hint={`已抽样本，共 ${nonStatSampleParameter.sampledResult?.sampledSize || 0} 个`}
                width={() => {
                  const itemElement = document.getElementById('nonStatSample_SampleMethodToolBar');
                  if (itemElement) {
                    return itemElement.offsetWidth - 600;
                  } else {
                    return window.innerWidth - 860;
                  }
                }}
                style={{ marginTop: 0, marginLeft: 20, paddingTop: 5, marginRight: 5 }}
                readOnly={true}
                tabIndex={-1}
                value={getValueTextTop500(
                  nonStatSampleParameter.sampledResult?.sampleTextFieldValues,
                )}
              />
              <div className="table-with-borders" style={{ border: 0 }}>
                <Button
                  text="查看"
                  hint="查看已抽取样本"
                  style={{ marginRight: 4 }}
                  onClick={async () => {
                    if (nonStatSampleParameter.sampledResult?.sampledSize) {
                      const whereSql = await getWhereSqlBySampleList(
                        sampleStepInfo,
                        nonStatSampleParameter.sampledResult?.sampledList || [],
                      );

                      viewSampleListByWhereSql(
                        '已抽样本',
                        nonStatSampleParameter.sampledResult?.sampledSize,
                        whereSql,
                      );
                    } else {
                      msgError('还没有抽取到样本!');
                    }
                  }}
                ></Button>
              </div>
            </div>
          </Item>

          <Item location="after">
            <Button
              text="试抽取"
              type="default"
              style={{ marginRight: 0 }}
              disabled={loading || nonStatSampleParameter.sampleMethod === SampleMethod.manual}
              onClick={async () => {
                //分层
                if (nonStatSampleParameter.sampleMethod === SampleMethod.layer) {
                  layerSampleRef.current?.saveEditData();
                  //  await layerSampleRef.current?.reCalcUnSampleSize(nonStatSampleParameter,true);
                }
                if (nonStatSampleParameter.sampleMethod === SampleMethod.pps) {
                  return msgError('请选择抽样方法!');
                }
                setLoading(true);
                try {
                  nonStatSampleParameter.sampledResult = await getTrySampleResult(
                    sampleStepInfo,
                    nonStatSampleParameter,
                  );
                  if (nonStatSampleParameter.sampledResult.sampledSize) {
                    msgInfo(`成功抽取 ${nonStatSampleParameter.sampledResult.sampledSize} 个!`);
                  }
                } finally {
                  setLoading(false);
                }
                // console.log('sampleStepInfo:', JSON.stringify(sampleStepInfo))
                setNonStatSampleParameter({ ...nonStatSampleParameter });
              }}
            ></Button>
          </Item>
        </Toolbar>

        {
          //任意抽样
          nonStatSampleParameter.sampleMethod == SampleMethod.random && (
            <div style={{ ...sampleMethodStyle }}>
              <RandomSample
                sampleParameterValues={nonStatSampleParameter}
                setSampleParameterValues={setNonStatSampleParameter}
              ></RandomSample>
            </div>
          )
        }
        {
          //系统抽样

          nonStatSampleParameter.sampleMethod == SampleMethod.system && (
            <div style={{ ...sampleMethodStyle }}>
              <SystemSample
                sampleParameterValues={nonStatSampleParameter}
                setSampleParameterValues={setNonStatSampleParameter}
                projectOverallProps={sampleStepInfo.projectOverallProps}
              ></SystemSample>
            </div>
          )
        }
        {
          //分层抽样

          nonStatSampleParameter.sampleMethod == SampleMethod.layer && (
            <div style={{ ...sampleMethodStyle }}>
              <LayerSample
                ref={layerSampleRef}
                sampleParameterValues={nonStatSampleParameter}
                setSampleParameterValues={setNonStatSampleParameter}
              ></LayerSample>
            </div>
          )
        }
        {nonStatSampleParameter.sampleMethod == SampleMethod.manual && (
          <div style={{ ...sampleMethodStyle }}>
            <ManualSample
              ref={manualSampleRef}
              sampleParameterValues={nonStatSampleParameter}
              setSampleParameterValues={setNonStatSampleParameter}
            ></ManualSample>
          </div>
        )}
        {/* 抽样结果2: 重大项目统计,特殊项目统计 */}
        {/* 
            {getSampledResultTable2(sampleStepInfo,nonStatSampleParameter)} */}

        {/* 抽样结果表1,已抽统计 */}
        {getSampledResultTable1(sampleStepInfo, nonStatSampleParameter)}

        <LoadPanel visible={loading} />
      </div>
    </ScrollView>
  );
});
